package com.anxin.common.utils;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.ArrayUtils;

public class RequestUtils {
	private static final String NGINX_IP_HEADER = "X-Real-IP";
	private static final String NGINX_X_Forwarded_For = "X-Forwarded-For";

	/**
	 * 功能描述: 获取ip（兼容nginx转发）
	 *
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ips = request.getHeader(NGINX_X_Forwarded_For);
		String[] ipArray = StringUtils.split(ips, ",");
		if (!ArrayUtils.isEmpty(ipArray)) {
			return StringUtils.trim(ipArray[0]);
		} else {
			String ip = request.getHeader(NGINX_IP_HEADER);
			if (StringUtils.isEmpty(ip)) {
				ip = request.getRemoteAddr();
			}
			return ip;
		}
	}

	/**
	 * 获取用户代理
	 */
	public static String getUserAgent(HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
		return userAgent;
	}

	/**
	 * 
	 * 功能描述: <br>
	 * 获取hostname
	 *
	 * @param request
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public static String getHostName(HttpServletRequest request) {
		String host = request.getHeader("Host");
		return host;
	}

	/**
	 * 
	 * 功能描述: <br>
	 * 获取所有请求参数
	 *
	 * @param request
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public static String getAllRequestParam(HttpServletRequest request) {
		StringBuilder sb=new StringBuilder();
		Enumeration enumeration = request.getParameterNames();
		while (enumeration.hasMoreElements()) {
			String thisName = enumeration.nextElement().toString();
			String thisValue = request.getParameter(thisName);
			sb.append(thisName).append("=").append(thisValue).append("&");
		}
		return sb.toString();
	}
}
